package com.md.common.utils.validate;

import com.md.common.exception.BaseErrorCode;
import com.md.common.utils.ApplicationContextProvider;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindException;
import org.springframework.validation.Errors;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;

/**
 * 功能描述：bean数据校验器
 *
 * @author lujianping@oak168.com
 * @version 1.0
 * @date 2017/9/12 10:30
 * @since JDK 1.8
 */
@Component
public class BeanValidator {

    private final static Logger logger = LoggerFactory.getLogger(BeanValidator.class);

    public static <T> ValidateResult validate(T obj, Object... groupValidator) {
        LocalValidatorFactoryBean validator =
                ApplicationContextProvider.getBean(LocalValidatorFactoryBean.class);
        final ValidateResult validateResult = new ValidateResult();
        Errors errors = new BindException(obj, obj.getClass().getName());
        validator.validate(obj, errors, groupValidator);
        if (errors.hasErrors()) {
            validateResult.setHasErrors(true);
            StringBuilder builder = new StringBuilder();
            errors.getFieldErrors()
                    .forEach(fe ->
            builder.append(formateErrorMsg(fe.getDefaultMessage()))
                    .append("<br/>"));
            if (errors.getErrorCount() >= 1) {
                validateResult.setErrorCode(BaseErrorCode.PARAMS_ERROR);
            }
            validateResult.setErrorMsg(builder.toString());
        }else{
            validateResult.setHasErrors(false);
            validateResult.setErrorMsg(new BaseErrorCode().getErrorMsg(BaseErrorCode.SUCCESSFUL));
        }
        return validateResult;
    }

    private static String formateErrorMsg(String message) {
        String errorCode = extractErrorCode(message);
        if (StringUtils.isNoneBlank(errorCode) && NumberUtils.isNumber(errorCode)) {
            return new BaseErrorCode().getErrorMsg(Integer.parseInt(errorCode));
        }
        return message;
    }

    private static String extractErrorCode(String message) {
        if (message.startsWith("#")) {
            return message.substring(1);
        }
        logger.warn("bean校验注解message不是以#开头，请确认");
        return message;
    }


}
